<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.normid" placeholder="规范编码" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.normdescribr" placeholder="规范描述" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSelectForm">重置</el-button>
        <el-button @click="getNormInfo()">查询</el-button>
        <el-button v-if="isAuth('norminfo:norminfo:save')" @click="addOrUpdateHandle()">新增</el-button>
<!--        <el-button v-if="isAuth('norminfo:norminfo:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>-->
        <el-button @click="submit" :disabled="disabled">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="normid"
        header-align="center"
        align="center"
        label="规范编码">
      </el-table-column>
      <el-table-column
        prop="normdescribr"
        header-align="center"
        align="center"
        label="规范描述">
      </el-table-column>
      <el-table-column
        prop="curcentral"
        header-align="center"
        align="center"
        label="电流中心值">
      </el-table-column>
      <el-table-column
        prop="curdown"
        header-align="center"
        align="center"
        label="电流下限偏离">
      </el-table-column>
      <el-table-column
        prop="curup"
        header-align="center"
        align="center"
        label="电流上限偏离">
      </el-table-column>
      <el-table-column
        prop="volcentral"
        header-align="center"
        align="center"
        label="电压中心值">
      </el-table-column>
      <el-table-column
        prop="voldown"
        header-align="center"
        align="center"
        label="电压下限偏离">
      </el-table-column>
      <el-table-column
        prop="volup"
        header-align="center"
        align="center"
        label="电压上限偏离">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="showBind(scope.row)">下发</el-button>
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.normid)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.normid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <normbind v-if="Visiable" ref="dialog"></normbind>
  </div>
</template>

<script>
  import AddOrUpdate from './norminfo-add-or-update'
  import normbind from './normbind'
  import xlsx from 'xlsx'
  import {Loading} from 'element-ui'
  export default {
    data () {
      return {
        dataForm: {
          key: '',
          normid: '',
          normdescribr: ''
        },
        disabled: false,
        loading: false,
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        Visiable: false,
        path:"ws://localhost:8089/renren-fast/websocket",
        socket:""
      }
    },
    components: {
      AddOrUpdate,
      normbind
    },
    mounted () {
      this.getNormInfotest()
      this.getNormInfo()
      this.init()
    },
    activated () {
      this.getDataList()
    },
    methods: {
      init: function () {
        if(typeof(WebSocket) === "undefined"){
          alert("您的浏览器不支持socket")
        }else{
          // 实例化socket
          this.socket = new WebSocket(this.path)
          // 监听socket连接
          this.socket.onopen = this.open
          // 监听socket错误信息
          this.socket.onerror = this.error
          // 监听socket消息
          this.socket.onmessage = this.getMessage
        }
      },
      open: function () {
        console.log("socket连接成功")
      },
      error: function () {
        console.log("连接错误")
      },
      getMessage: function (event) {
         console.log(event.data)
        // var alarmArray = [];
        // var newAlarm = JSON.parse(event.data);
       // this.dataList.push(JSON.parse(event.data));
        // 将消息数组转换为JSON字符串，并输出
        // var jsonString = JSON.stringify(alarmArray);
        // this.dataList.push(alarmArray);
       // console.log(this.dataList);

      },
      send: function () {
        this.socket.send(params)
      },
      close: function () {
        console.log("socket已经关闭")
      },
      getNormInfotest(){
        // console.log("焊机："+this.label)
        // console.log("开始时间："+this.value1[0])
        // console.log("结束时间："+this.value1[1])
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/norminfo/norminfo/getnorminfo'),
          method: 'get',
          params: this.$http.adornParams({
            'normid': this.dataForm.normid,
            'normdescribr': this.dataForm.normdescribr,
          })
        }).then(({data}) => {
          if (data) {
            //console.log(data)
            this.dataListtest = data
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      getNormInfo(){
        // console.log("焊机："+this.label)
        // console.log("开始时间："+this.value1[0])
        // console.log("结束时间："+this.value1[1])
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/norminfo/norminfo/getnorminfo'),
          method: 'get',
          params: this.$http.adornParams({
            'normid': this.dataForm.normid,
            'normdescribr': this.dataForm.normdescribr,
          })
        }).then(({data}) => {
          if (data) {
            //console.log(data)
            this.dataList = data
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 重置按钮
      resetSelectForm(){
        this.dataForm.normid = '';
        this.dataForm.normdescribr = '';
        this.getNormInfo();
      },
      // 导出操作
      submit(){
        if(this.dataListSelections.length <= 0){
          this.$message({
            message: "请选择需要导出的数据!",
            type: 'warning',
            showClose: true
          });
          return;
        }
        this.disabled = true;
        let loadingInstance = Loading.service({
          text: "正在导出...",
          background: "rgba(0,0,0,.5)"
        });
        let arr = this.dataListSelections.map(item => {
          console.log(item)
          return {
            规范编码: item.normid,
            规范描述: item.normdescribr,
            电流中心值: item.curcentral,
            电流下限偏离: item.curdown,
            电流上限偏离: item.curup,
            电压中心值: item.volcentral,
            电压下限偏离: item.voldown,
            电压上限偏离: item.volup
          };
        });
        //console.log(arr)
        let sheet = xlsx.utils.json_to_sheet(arr);
        const book1 = xlsx.utils.book_new();
        xlsx.utils.book_append_sheet(book1,sheet,"sheet1");
        xlsx.writeFile(book1,`user${new Date().getTime()}.xls`);
        loadingInstance.close();
        this.disabled = false;
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/norminfo/norminfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      //打开规范下发页面
      showBind (row) {  // 获取到所点击的那一行的employeeId
        this.Visiable = true;
        this.$nextTick(() => {
          this.$refs.dialog.init(row);
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.normid
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/norminfo/norminfo/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      }
    }
  }
</script>
